package com.jsb.laundry.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.jsb.laundry.common.config.Constant;
import com.jsb.laundry.common.enums.ReturnStatusCode;
import com.jsb.laundry.common.response.WebResponse;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.baidu.CalLngLatUtil;
import com.jsb.laundry.dao.OrdersFulfillmentDao;
import com.jsb.laundry.dao.OrdersFulfillmentItemDao;
import com.jsb.laundry.model.dto.HistoricalOrdersRequest;
import com.jsb.laundry.model.dto.OrderInfoListRequest;
import com.jsb.laundry.model.dto.RiderIdAndOrderInfoRequest;
import com.jsb.laundry.model.dto.SeizeOrdersRequest;
import com.jsb.laundry.model.entity.Flaw;
import com.jsb.laundry.model.entity.JsbOrdersFulfillment;
import com.jsb.laundry.model.entity.JsbOrdersFulfillmentItem;
import com.jsb.laundry.model.vo.*;
import com.jsb.laundry.service.*;
import com.jsb.laundry.service.impl.JsbOrderStatusLogServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@Api(tags = {"骑手订单"})
@RestController
@RequestMapping("/order/")
public class OrderListController {
    @Resource
    private OrderInfoService orderInfoService;
    @Resource
    private ServeService serveService;
    @Resource
    private OrdersFulfillmentService ordersFulfillmentService;
    @Resource
    private OrdersFulfillmentDao ordersFulfillmentDao;
    @Resource
    private OrdersFulfillmentItemDao ordersFulfillmentItemDao;
    @Resource
    private OrderSplittingServiceImpl orderSplittingService;
    @Resource
    private JsbOrderStatusLogServiceImpl jsbOrderStatusLogService;
    @ApiOperation(value = "抢单列表", notes = "抢单列表", httpMethod = "POST")
    @PostMapping("list")
    public WebResponse list(@RequestBody OrderInfoListRequest orderInfoListRequest) {
        String byUserLogin = orderInfoService.findByUserLogin(orderInfoListRequest.getUserId());

        PageHelper.startPage(orderInfoListRequest.getPageNum(), orderInfoListRequest.getPageSize());
        List<OrderListVo> byUserInfoList = orderInfoService.findByUserInfoList();
        for (OrderListVo orderListVo : byUserInfoList) {
            String money = orderListVo.getMoney();
            double moneys = Integer.parseInt(money) * Constant.rider_commission_percentage;
            orderListVo.setMoney(JSBUtil.turnDoubleStrNew(moneys));
        }
        if ("1".equals(byUserLogin)) {
            return WebResponse.successData(byUserInfoList);
        }
        return WebResponse.successData(null);
    }

    @ApiOperation(value = "用户在线状态", notes = "用户在线状态", httpMethod = "POST")
    @PostMapping("userStatus")
    public WebResponse userStatus(@RequestBody SeizeOrdersRequest seizeOrdersRequest) {
        String byUserLogin = orderInfoService.findByUserLogin(seizeOrdersRequest.getRiderId());
        return WebResponse.successData(byUserLogin);
    }

    @Transactional
    @ApiOperation(value = "骑手抢单", notes = "骑手抢单", httpMethod = "POST")
    @PostMapping("seizeOrders")
    public WebResponse SeizeOrders(@RequestBody SeizeOrdersRequest seizeOrdersRequest) {

        String byUserLogin = orderInfoService.findByUserLogin(seizeOrdersRequest.getRiderId());
        if ("0".equals(byUserLogin)) {

            return WebResponse.success(ReturnStatusCode.PLEASE_SELECT_LOGIN_STATUS.getCode(), ReturnStatusCode.PLEASE_SELECT_LOGIN_STATUS.getMsg());
        }
        if (JSBUtil.isEmptyString(seizeOrdersRequest.getOrderId()) || JSBUtil.isEmptyString(seizeOrdersRequest.getRiderId())) {
            return WebResponse.success(ReturnStatusCode.PLEASE_ENTER_THE_NECESSARY_PARAMETERS.getCode(), ReturnStatusCode.PLEASE_ENTER_THE_NECESSARY_PARAMETERS.getMsg());
        }
        //上岗考次数
        if (serveService.findByQuestionLog(seizeOrdersRequest.getRiderId())==0){
            return WebResponse.success(ReturnStatusCode.FAILURE_TO_PASS_THE_ON_THE_JOB_EXAM.getCode(), ReturnStatusCode.FAILURE_TO_PASS_THE_ON_THE_JOB_EXAM.getMsg());
        }
        //判断分数是否达到
        if (serveService.findByUserIdFraction(seizeOrdersRequest.getRiderId())<99){
            return WebResponse.success(ReturnStatusCode.FAILURE_TO_PASS_THE_ON_THE_JOB_EXAM.getCode(), ReturnStatusCode.FAILURE_TO_PASS_THE_ON_THE_JOB_EXAM.getMsg());
        }
        //判断改用户是否购买理约金
        if (serveService.findByUserIdOkFlag(seizeOrdersRequest.getRiderId()) == 0) {
            return WebResponse.success(ReturnStatusCode.WX_FLAG.getCode(), ReturnStatusCode.WX_FLAG.getMsg());
        }

        int byOrderNum = orderInfoService.findByOrderNum(seizeOrdersRequest.getOrderId());


        //查询该订单方向
        int byOrderDirection = orderInfoService.findByOrderDirection(seizeOrdersRequest.getOrderId());
        //防止骑手重复抢单
        int repeat = orderInfoService.repeat(seizeOrdersRequest.getOrderId(), String.valueOf(byOrderDirection));
        if (repeat==1){
            return WebResponse.success(ReturnStatusCode.REPEAT.getCode(), ReturnStatusCode.REPEAT.getMsg());
        }
        int num = 1;
        String orderFulfillmentsId = "";
        String flag = "";
        String trackingNumber = "qs"+JSBUtil.generateLongOrderId();
        DeliveryOrderInformationVo byOrderInfo = orderInfoService.findByOrderInfo(seizeOrdersRequest.getOrderId());
        JsbOrdersFulfillment jsbOrdersFulfillment = new JsbOrdersFulfillment();
        jsbOrdersFulfillment.setOrderId(seizeOrdersRequest.getOrderId());
        jsbOrdersFulfillment.setTrackingCode("jsb");//物流公司编码
        jsbOrdersFulfillment.setTrackingCompany("聚申宝");//物流公司编码
        jsbOrdersFulfillment.setTrackingDirection(String.valueOf(byOrderDirection));//订单方向
        jsbOrdersFulfillment.setTrackingCarrierId(seizeOrdersRequest.getRiderId());//骑手id
        jsbOrdersFulfillment.setCustomerName(byOrderInfo.getCustomerName());//客户姓名
        jsbOrdersFulfillment.setCustomerTel(byOrderInfo.getCustomerTel());//客户电话
        if (byOrderDirection == 1){
            jsbOrdersFulfillment.setPickupAddress(byOrderInfo.getPickupAddress());//取货地址
            jsbOrdersFulfillment.setDeliveryAddress(byOrderInfo.getDeliveryAddress());//送货地址
            orderFulfillmentsId = "ls"+seizeOrdersRequest.getOrderId()+"-";
        }else if (byOrderDirection == 2){
            flag="A";
            jsbOrdersFulfillment.setPickupAddress(byOrderInfo.getDeliveryAddress());//取货地址
            jsbOrdersFulfillment.setDeliveryAddress(byOrderInfo.getPickupAddress());//送货地址
            //更改小站订单状态
            int updateShopsStatus = ordersFulfillmentDao.updateShopsStatus(seizeOrdersRequest.getOrderId());
            orderFulfillmentsId = "ls"+seizeOrdersRequest.getOrderId()+"-";
        }
        //向订单物流表添加
        jsbOrdersFulfillment.setTrackingNumber(trackingNumber);//物流编号
        ordersFulfillmentDao.insert(jsbOrdersFulfillment);
        //查询订单详情
        List<FindByOrderInfoItemVo> byOrderInfoItem = ordersFulfillmentDao.findByOrderInfoItem(seizeOrdersRequest.getOrderId());

        JsbOrdersFulfillmentItem ordersFulfillmentItem = new JsbOrdersFulfillmentItem();
        for (FindByOrderInfoItemVo findByOrderInfoItemVo : byOrderInfoItem) {
            ordersFulfillmentItem.setOrderItemId(findByOrderInfoItemVo.getSubOrderId());//订单明细表id

            ordersFulfillmentItem.setOrderFulfillmentsId(orderFulfillmentsId+num+++flag);//订单子物流表id
            ordersFulfillmentItem.setTrackingNumber(findByOrderInfoItemVo.getTrackingNumber());//订单物流表id
            ordersFulfillmentItem.setProductId(findByOrderInfoItemVo.getProductId());//商品id
            ordersFulfillmentItem.setQuantity(findByOrderInfoItemVo.getQuantity());//发货商品数量
            ordersFulfillmentItem.setOrderDirection(String.valueOf(byOrderDirection));//订单方向
            ////向订单物流商品明细表添加
            ordersFulfillmentItemDao.addOrdersFulfillmentItem(ordersFulfillmentItem);
        }

        //更改主订单的状态
        int updateOrderStatus = orderInfoService.updateOrderStatus(seizeOrdersRequest.getOrderId());
        //查询改订单的金额
//        int byPaidPrice = orderInfoService.findByPaidPrice(seizeOrdersRequest.getOrderId());
//        double money = byPaidPrice * Constant.rider_commission_percentage;
        if (updateOrderStatus == 1) {
            int direction = orderInfoService.findByOrderDirection(seizeOrdersRequest.getOrderId());
            String byOrderStatus = orderInfoService.findByOrderStatus(seizeOrdersRequest.getOrderId());
            jsbOrderStatusLogService.addLog(seizeOrdersRequest.getOrderId(),byOrderStatus, String.valueOf(direction));
        }

        return WebResponse.successData(updateOrderStatus);
    }
    //TODO 抢单有问题
    @ApiOperation(value = "查看抢单列表", notes = "查看抢单列表", httpMethod = "POST")
    @PostMapping("viewOrderGrabbingList")
    public WebResponse ViewOrderGrabbingList(@RequestBody RiderIdAndOrderInfoRequest riderIdAndOrderInfoRequest) {
        if (JSBUtil.isEmptyString(riderIdAndOrderInfoRequest.getRiderId()) || JSBUtil.isEmptyString(riderIdAndOrderInfoRequest.getOrderStatus())) {
            return WebResponse.success(ReturnStatusCode.PLEASE_ENTER_THE_NECESSARY_PARAMETERS.getCode(), ReturnStatusCode.PLEASE_ENTER_THE_NECESSARY_PARAMETERS.getMsg());
        }
        PageHelper.startPage(riderIdAndOrderInfoRequest.getPageNum(), riderIdAndOrderInfoRequest.getPageSize());
        List<OrderListVo> orderListVos = orderInfoService.afterTheRiderSnatchedTheOrderInfo(riderIdAndOrderInfoRequest.getRiderId(), riderIdAndOrderInfoRequest.getOrderStatus(), "1");
        for (OrderListVo orderListVo : orderListVos) {
            //查询改订单的金额
            int byPaidPrice = orderInfoService.findByPaidPrice(orderListVo.getOrderId());
            double money = byPaidPrice * Constant.rider_commission_percentage;
            orderListVo.setMoney(JSBUtil.turnDoubleStrNew(money));
            orderListVo.getUserInfo().setUserXY(CalLngLatUtil.getLngLat(orderListVo.getUserInfo().getUserAddress()));

        }
        return WebResponse.successData(orderListVos);
    }

    @ApiOperation(value = "查看抢单列表", notes = "查看抢单列表", httpMethod = "POST")
    @PostMapping("viewOrderGrabbingListBack")
    public WebResponse ViewOrderGrabbingListBack(@RequestBody RiderIdAndOrderInfoRequest riderIdAndOrderInfoRequest) {
        if (JSBUtil.isEmptyString(riderIdAndOrderInfoRequest.getRiderId()) || JSBUtil.isEmptyString(riderIdAndOrderInfoRequest.getOrderStatus())) {
            return WebResponse.success(ReturnStatusCode.PLEASE_ENTER_THE_NECESSARY_PARAMETERS.getCode(), ReturnStatusCode.PLEASE_ENTER_THE_NECESSARY_PARAMETERS.getMsg());
        }
        PageHelper.startPage(riderIdAndOrderInfoRequest.getPageNum(), riderIdAndOrderInfoRequest.getPageSize());
        List<OrderListVo> orderListVos = orderInfoService.afterTheRiderSnatchedTheOrderInfo(riderIdAndOrderInfoRequest.getRiderId(), riderIdAndOrderInfoRequest.getOrderStatus(), "2");
        for (OrderListVo orderListVo : orderListVos) {
            //查询改订单的金额
            int byPaidPrice = orderInfoService.findByPaidPrice(orderListVo.getOrderId());
            double money = byPaidPrice * Constant.rider_commission_percentage;
            orderListVo.setMoney(JSBUtil.turnDoubleStrNew(money));
            orderListVo.getUserInfo().setUserXY(CalLngLatUtil.getLngLat(orderListVo.getUserInfo().getUserAddress()));

        }
//        if ("9".equals(riderIdAndOrderInfoRequest.getOrderStatus())) {
//            PageHelper.startPage(riderIdAndOrderInfoRequest.getPageNum(), riderIdAndOrderInfoRequest.getPageSize());
//            List<OrderListVo> list = orderInfoService.okOrderInfo(riderIdAndOrderInfoRequest.getRiderId());
//            for (OrderListVo orderListVo : list) {
//                //查询改订单的金额
//                int byPaidPrice = orderInfoService.findByPaidPrice(orderListVo.getOrderId());
//                double money = byPaidPrice * Constant.rider_commission_percentage;
//                orderListVo.setMoney(JSBUtil.turnDoubleStrNew(money));
//                orderListVo.getUserInfo().setUserXY(CalLngLatUtil.getLngLat(orderListVo.getUserInfo().getUserAddress()));
//
//            }
//            return WebResponse.successData(list);
//        }
        return WebResponse.successData(orderListVos);
    }

    @ApiOperation(value = "查看已交接 弃用", notes = "查看已交接", httpMethod = "POST")
    @PostMapping("viewHandover")
    public WebResponse viewHandover(@RequestBody OrderInfoListRequest orderInfoListRequest) {

        PageHelper.startPage(orderInfoListRequest.getPageNum(), orderInfoListRequest.getPageSize());
        List<OrderListVo> orderListVos = orderInfoService.viewHandover(orderInfoListRequest.getUserId());
        for (OrderListVo orderListVo : orderListVos) {
            //查询改订单的金额
            int byPaidPrice = orderInfoService.findByPaidPrice(orderListVo.getOrderId());
            double money = byPaidPrice * Constant.rider_commission_percentage;
            orderListVo.setMoney(JSBUtil.turnDoubleStrNew(money));

        }
        return WebResponse.successData(orderListVos);
    }

    @ApiOperation(value = "查看订单详情子订单", notes = "查看订单详情子订单", httpMethod = "POST")
    @PostMapping("viewOrderDetails")
    public WebResponse viewOrderDetails(@RequestBody JSONObject object) {
        String orderId = object.getString("orderId");
        List<OrderDetailsVo> bySybOrderIdList = orderInfoService.findBySybOrderIdList(orderId);
        return WebResponse.successData(bySybOrderIdList);
    }

    @ApiOperation(value = "取件异常 待定", notes = "取件异常 待定", httpMethod = "POST")
    @PostMapping("abnormalPickup")
    public WebResponse abnormalPickup() {

        return WebResponse.successData(1);
    }

    @ApiOperation(value = "历史订单", notes = "历史订单", httpMethod = "POST")
    @PostMapping("historicalOrders")
    public WebResponse historicalOrders(@RequestBody HistoricalOrdersRequest historicalOrdersRequest) {
        if (JSBUtil.isEmptyString(historicalOrdersRequest.getUserId())){

        }
        PageHelper.startPage(historicalOrdersRequest.getPageNum(), historicalOrdersRequest.getPageSize());
        List<HistoricalOrdersVo> byHistoricalOrders = ordersFulfillmentDao.findByHistoricalOrders(historicalOrdersRequest);
        for (HistoricalOrdersVo byHistoricalOrder : byHistoricalOrders) {
            if ("e".equals(byHistoricalOrder.getOrderStatus())){
                byHistoricalOrder.setOrderStatus("1");
            }
            else {
                byHistoricalOrder.setOrderStatus("2");
            }
        }
        return WebResponse.successData(byHistoricalOrders);
    }


    @ApiOperation(value = "查询瑕疵", notes = "查询瑕疵", httpMethod = "POST")
    @PostMapping("findByFlaw")
    public WebResponse findByFlaw(@RequestBody String data) {
        JSONObject jsonObject = JSON.parseObject(data);
        String type = jsonObject.getString("type");
        String keyword = jsonObject.getString("keyword");
        List<Flaw> byFlaw = orderInfoService.findByFlaw(keyword,type);
        return WebResponse.successData(byFlaw);
    }

    @ApiOperation(value = "查询瑕疵类型", notes = "查询瑕疵类型", httpMethod = "POST")
    @PostMapping("findByFlawType")
    public WebResponse findByFlawType() {
        return WebResponse.successData(orderInfoService.findByFlawType());
    }

    @ApiOperation(value = "查询配饰", notes = "查询配饰", httpMethod = "POST")
    @PostMapping("findByAccessories")
    public WebResponse findByAccessories(@RequestBody JSONObject object) {
        String keyword = object.getString("keyword");
        return WebResponse.successData(orderInfoService.findByAccessories(keyword));
    }

    @ApiOperation(value = "查询品牌", notes = "查询品牌", httpMethod = "POST")
    @PostMapping("findByBrand")
    public WebResponse findByBrand(@RequestBody JSONObject object) {
        String keyword = object.getString("keyword");
        return WebResponse.successData(orderInfoService.findByBrand(keyword));
    }

    @ApiOperation(value = "查询效果", notes = "查询效果", httpMethod = "POST")
    @PostMapping("findByEffect")
    public WebResponse findByEffect(@RequestBody JSONObject object) {
        String keyword = object.getString("keyword");
        return WebResponse.successData(orderInfoService.findByEffect(keyword));
    }

    @ApiOperation(value = "查询颜色", notes = "查询颜色", httpMethod = "POST")
    @PostMapping("findByColour")
    public WebResponse findByColour(@RequestBody JSONObject object) {
        String keyword = object.getString("keyword");
        return WebResponse.successData(orderInfoService.findByColour(keyword));
    }

    @ApiOperation(value = "打印单号", notes = "打印单号", httpMethod = "POST")
    @PostMapping("printOrderNumber")
    public WebResponse printOrderNumber(@RequestBody JSONObject data) {
        String orderId = data.getString("orderId");
        List<PrintOrderNumberVo> printOrderNumberVos = ordersFulfillmentDao.printOrderNumber(orderId);
        return WebResponse.successData(printOrderNumberVos);
    }
}
